package com.reeygu.base;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

class MyTask extends RecursiveTask<Integer> {

    private static final Integer VALUE = 10;
    private int start;
    private int end;
    private int result;

    //创建有参构造
    public MyTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    //拆分和合并过程
    @Override
    protected Integer compute() {
        //判断相加两个值的差是否大于10
        if((end - start) > VALUE) {
            int midl = (end - start) / 2;
            MyTask taskOne = new MyTask(start, midl);
            MyTask taskTow = new MyTask(midl + 1, end);
            taskOne.fork();
            taskTow.fork();
            result = taskOne.join() + taskTow.join();
        } else {
            for (int i = start; i <= end; i++) {
                result += i;
            }
        }
        return result;
    }
}

/**
 * 测试分支合并任务的实现，理解ForkJoinPool的使用
 */
public class ForkAndJoin {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyTask task = new MyTask(1, 100);
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Integer> submit = forkJoinPool.submit(task);
        int result = submit.get();
        System.out.println(result);
        forkJoinPool.shutdown();
    }
}
